package cn.edu.hit;

import java.util.HashMap;
import java.util.Map;
import java.util.function.Function;

/**
 * Created by Wang on 2018/9/14.
 */
public class ObjectCacheUtils<K, E> {
    protected Map<K, E> cacheMap = new HashMap<>();
    protected Function<K, E> provider;

    public ObjectCacheUtils(Function<K, E> provider) {
        this.provider = provider;
    }

    public E get(K key) {
        if (cacheMap.containsKey(key)) {
            return cacheMap.get(key);
        } else {
            E e = provider.apply(key);
            cacheMap.put(key, e);
            return e;
        }
    }

    public void set(K key, E e) {
        cacheMap.put(key, e);
    }

    public void putAll(Map<? extends K, ? extends E> m) {
        cacheMap.putAll(m);
    }

    public boolean containsKey(K key) {
        return cacheMap.containsKey(key);
    }
}
